<template>
    <div class="page__all">
        
        <div class="page__info__row">
            
            <div class="page__title">
                生成记录
            </div>

            <div class="generate__info">
                
                <span><svg-icon name="icon-suanli" :size="25" style="color: var(--wchime-color-coin);"></svg-icon></span>
                {{ userStore.user_membership?userStore.user_membership.total - userStore.user_membership.use_number:"---"  }}
            </div>
        </div>

        <div class="page__record" ref="recordRef" @scroll="handScrollRecord">
            
            <Waterfall :lazyload="false" :breakpoints="breakpoints" :gutter="10" :list="list" @load="loadMore">
                <template #item="{ item, url, index }">
                    <div class="card_content"  @click="click_record(item)" ref="videoPlayers" 
                    @mouseenter="playVideo(index, item)"@mouseleave="pauseVideo(index, item)">

                    <div  v-if="item.state==3 && item.result_list[0].file_type=='png'" class="card_img water__items">
                        <LazyImg class="cover" :url="item.result_list[0].path_url" />
                    </div>
                    <div class="water__items video__contains" v-else-if="item.state==3 && item.result_list[0].file_type=='mp4'">
                        <video muted :src="item.result_list[0].path_url" style="width: 100%; height: 100%; object-fit: contain;"></video>
                        <span class="video__icon"><svg-icon name="icon-shipin" :size="30"></svg-icon></span>
                    </div>

                    <div class="water__items audio__contains" v-else-if="item.state==3 && item.result_list[0].file_type=='mp3'">
                        <audio :src="item.result_list[0].path_url" controls style="width: 100%; object-fit: contain;"></audio>
                    </div>

                    <div class="water__items" v-else-if="item.state==-1">
                        <div class="fail__box">
                            生成失败！
                        </div>
                    </div>

                    <div class="water__items" v-else-if="item.state==1">
                        <div class="wait__box">
                            排队中
                        </div>
                    </div>

                    <div class="water__items" v-else-if="item.state==2">
                        <div class="generate__box">
                            生成中
                        </div>
                    </div>

                    <div class="water__items" v-else>
                        <div class="unknow__box">
                            未知状态
                        </div>
                    </div>


                    
                    </div>
                </template>
            </Waterfall>

            <div v-if="!ableLoadMore" class="scroll__botton">已经加载全部~</div>
        </div>


        <RecordDialog
            @cancel="cancel"
            :visible="isVisible"
            :instance="click_instance"
        ></RecordDialog>
    </div>
</template>
           
<script setup>
    import { ref, onMounted, onUnmounted } from "vue"
    import { LazyImg, Waterfall } from 'vue-waterfall-plugin-next'
    import RecordDialog from '../public/RecordDialog.vue'
    import 'vue-waterfall-plugin-next/dist/style.css'
    import {getGenerate, selectGenerate} from '@/api/homeApi.js'
    import { useUserStore } from '@/stores/user'

    const userStore = useUserStore()

    const props = defineProps(["instance"])
    const emit = defineEmits([])
    

    const data_obj = ref(props.instance)
    const point = ref(99999)
    const videoPlayers = ref([]);

    const isVisible = ref(false)
    const click_instance = ref({})

    const ableLoadMore = ref(true)
    const recordRef = ref(null)
    const loading = ref(false)
    
    const breakpoints = ref({
      1600: {
        rowPerView: 5,
      },
      1200: {
        rowPerView: 4,
      },
      800: {
        rowPerView: 2,
      },
    })

    const currentPage = ref(1)
    const pageSize = ref(30)
    const total = ref(0)
    const list = ref([])

    const select_interval = ref(null)


    // 插入第一条数据
    const insert_data = (item)=>{

        list.value.unshift(item)

        start_select_generate()

        userStore.setUsePoint(data_obj.value.point)
    }

    // 获取生成记录
    const getGenerateList = async ()=>{
        var req_data = {
            page: currentPage.value,
            page_size: pageSize.value,
            menu_id: data_obj.value.id
        }

        var res = await getGenerate(req_data)
        var res_data = res.data

        list.value = [...list.value, ...res_data.list]
        total.value = res_data.total
        if(total.value <= list.value.length){
            ableLoadMore.value = false
        }
        // console.log(list.value)
    }

    // 获取生成记录
    const mountedGetGenerateList = async ()=>{
        list.value = []
        var req_data = {
            page: currentPage.value,
            page_size: pageSize.value,
            menu_id: data_obj.value.id
        }

        var res = await getGenerate(req_data)
        var res_data = res.data
        list.value = [...list.value, ...res_data.list]
        total.value = res_data.total
        if(total.value <= list.value.length){
            ableLoadMore.value = false
        }
        start_select_generate()
        // console.log(list.value)
    }

    function click_record(instance){
      isVisible.value = true
      click_instance.value = instance
    }

    function cancel(){
      isVisible.value = false
      
    }

    const handScrollRecord = ()=>{
        // console.log(recordRef.value.scrollHeight- (recordRef.value.scrollTop + recordRef.value.clientHeight))
        if (ableLoadMore.value && recordRef.value.scrollHeight - (recordRef.value.scrollTop + recordRef.value.clientHeight) <= 10){
            loadMore()
        }
    }

    function loadMore(){
        // console.log('loadMore')
        try{
           setTimeout(()=>{
            if (loading.value) return
            loading.value = true
            currentPage.value += 1

            getGenerateList()

           }, 100)
        } catch(error) {
            console.log(error)
        } finally{
            loading.value = false
        }
    //     console.log(list.value)
    }

    const playVideo = (index, item) => {

        if (item.state==3 && item.result_list[0].file_type=='mp4'){
            var dom_list = document.getElementsByClassName('water__items')
            var video = dom_list[index].getElementsByTagName('video')[0]
        
            // console.log('播放', dom_list[index], video)
            video.loop = true
            video.play()
            
        }

    };

    const pauseVideo = (index, item) => {
        if (item.state==3 && item.result_list[0].file_type=='mp4'){
            var dom_list = document.getElementsByClassName('water__items')
            var video = dom_list[index].getElementsByTagName('video')[0]
        
            video.pause()
            // video.currentTime = 0;
            
        }
    };

    const selectGenerates = async()=>{

        var g_list = list.value.filter((item) => {
            return item.state == 1 || item.state == 2
        })
        var id_list = g_list.map(item => item.id)
        if (id_list.length>0){
            var req_data = {
                id: id_list
            }

            var res = await selectGenerate(req_data)

            if(res.code != 1){
                return
            }
            var res_data = res.data

            for (var i=0; i<res_data.length; i++){
                var it = list.value.filter(item => item.id == res_data[i].id)
                if(it.length>0){
                    list.value[list.value.indexOf(it[0])] = res_data[i]
                }
            }   

        }else{
            clear_select_interval()
        }   
        
    }

    const clear_select_interval = ()=>{
        if (select_interval.value){
            clearInterval(select_interval.value)
            select_interval.value = null
        }
    }

    const loop_select_generate = ()=>{
        select_interval.value = setInterval(()=>{
            selectGenerates()
        }, 10000)
    }

    const start_select_generate = ()=>{
        // console.log('开始查询任务状态')
        setTimeout(()=>{
            if (!select_interval.value){
                loop_select_generate()
            }
        }, 500)
        
    }

    const remove_select_generate = ()=>{
        // console.log('移除查询任务状态')
        setTimeout(()=>{
            clear_select_interval()
        }, 500)
        
    }

    defineExpose({insert_data, start_select_generate, remove_select_generate})

    onMounted(()=>{
        
         if (userStore.isLoggedIn){
            mountedGetGenerateList()
        }else{
            
            userStore.goLogin()
        }
    })

    onUnmounted(()=>{
        clear_select_interval()
    })
    
</script>
<style scoped lang="scss">

.water__items{
    position: relative;
    background-color: var(--wchime-bg-color-box);
    .time__span{
        width: 100%;
        position: absolute;
        bottom: 5px;
        left: 0;
        font-size: 14px;
        color: #fff;

    }
}
    .card_content{
        cursor: pointer;
        .card_img{
            border: solid 1px var(--wchime-color-border);
            border-radius: 6px;
            overflow: hidden;
        }
        video{
            border: solid 1px var(--wchime-color-border);
            border-radius: 6px;
        }
        .fail__box{
            border: solid 1px var(--wchime-color-border);
            height: 200px;
            border-radius: 6px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #ff0000;
        }
        .wait__box{
            border: solid 1px var(--wchime-color-border);
            height: 200px;
            border-radius: 6px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #bcb23e;
        }
        .generate__box{
            border: solid 1px var(--wchime-color-border);
            height: 200px;
            border-radius: 6px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #4c76e8;
        }
        .unknow__box{
            border: solid 1px var(--wchime-color-border);
            height: 200px;
            border-radius: 6px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #6c7070;
        }
        .video__contains{
            position: relative;
            .video__icon{
                position: absolute;
                top: 5px;
                right: 5px;
            }
        }

        .audio__contains{
            border: solid 1px var(--wchime-color-border);
            height: 150px;
            border-radius: 6px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

    }
    .page__all{
        width: 100%;
        height: 100%;
        padding: 10px 0 10px 10px;
        .page__info__row{
            width: 100%;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-right: 20px;
            .page__title{
                font-size: 20px;

            }
            .generate__info{
                cursor: pointer;
                border: 1px solid var(--wchime-color-border);
                display: flex;
                align-items: center;
                padding: 3px 8px;
                border-radius: 20px;
                color: var(--wchime-color-coin);
            }
        }

        .page__record{
            width: 100%;
            height: calc(100% - 40px);
            overflow-y: scroll;

            .scroll__botton{
                width: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                color: var(--wchime-color-text);
                font-size: 12px;
                font-weight: 400;
            }
        }
    }
</style>